// ==UserScript==
// @name        %youtube-Subtitle-translate%
// @namespace   %namespace%
// @description %description%
// @author      Author
// @include     *
// @exclude     %exclude%
// @require      https://code.jquery.com/jquery-1.12.4.js
// @require      https://code.jquery.com/ui/1.12.1/jquery-ui.js
// @version     1
// @grant       GM_xmlhttpRequest
// @grant       GM_getValue
// @grant       GM_setValue
// ==/UserScript==
// ===============================================
var doc_url = document.URL;
var btn_id = "test";
var btn_id_key = `#${btn_id}`

var en_arr;
var cn_arr;
// Page first time load
$(document).ready(function () { init(); });
// Page jump
window.addEventListener('spfdone', function (e) { init(); });

function init()
{
    get_subtitle();
    toggleToChinese()
}
function init2()
{
    openSubtitle();
    // Put button on page
    $('#eow-title').append(`<a id="${btn_id}">自动翻译字幕</a>`);

    // Style
    $(`#${btn_id}`).addClass('start yt-uix-button yt-uix-button-text yt-uix-tooltip'); // 样式是 Youtube 自带的.
    $(`#${btn_id}`).css('margin-top', '2px')
        .css('margin-left', '4px')
        .css('border', '1px solid rgb(0, 183, 90)')
        .css('cursor', 'pointer')
        .css('color', 'rgb(255, 255, 255)')
        .css('border-top-left-radius', '3px')
        .css('border-top-right-radius', '3px')
        .css('border-bottom-right-radius', '3px')
        .css('border-bottom-left-radius', '3px')
        .css('background-color', '#00B75A');

    var TITLE = unsafeWindow.ytplayer.config.args.title;
    document.getElementById(btn_id).addEventListener("click", translateSubtitle, false);
}
//执行
function translateSubtitle()
{
    // testTanslate();
    // get_subtitle()
    openSubtitle();
}

//打开字幕
function openSubtitle()
{
    var openBtn = document.querySelector("#movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-right-controls > button.ytp-subtitles-button.ytp-button");
    if (openBtn.getAttribute("aria-pressed") != "true") {
        openBtn.click();
    }
}

//测试翻译
async function testTanslate()
{
    var res = await translate("hello");
    console.log(res);
    res = await translate("google");
    console.log(res);
}
//google 翻译
function translate(txt)
{
    return new Promise(
        function (resolve, reject)
        {
            //var URL = "http://www.google.com/translate_t&langpair=auto|auto?text=" + txt + "&langpair=auto|auto";
            var URL = "https://translate.google.com/?langpair=auto|auto&text=" + txt;
            GM_xmlhttpRequest(
                {
                    method: 'GET',
                    url: URL,
                    headers: { "User-agent": navigator.userAgent, "Accept": "text/html" }, //"Accept": "text/html"
                    onload: function (response)
                    {
                        if (response.status == 200) {
                            var doc = new DOMParser().parseFromString(response.responseText, "text/html");
                            var rb = doc.getElementById("result_box");
                            resolve(rb.textContent);
                        }
                        else {
                            resolve("翻译失败:" + response.status);
                            console.error("status: ", response.status);
                        }
                    }
                }
            );
        }
    )
}

// if there are no subtitle, tell user that by change text and button style.
// 如果没有字幕 那么修改按钮的显示
function noAutoSubtitleHint()
{
    $(btn_id_key).text("No Auto Subtitle | 没有自动字幕");
    $(btn_id_key).css("background-color", "rgb(0, 0, 0)").css('border', '1px solid rgb(0, 0, 0)');
}

//获得字幕 
function get_subtitle()
{
    var TTS_URL = yt.getConfig("TTS_URL"); // <- if that one not wokring, try: yt.config.get("TTS_URL");
    // var lang_code = 'zh-CN';
    if (!TTS_URL) {
        console.log("Auto Subtitle Download: No TTS_URL");
        noAutoSubtitleHint();
        return false;
    }
    // following 2 line is to get a URL, URL is important, is where we get the subtitle from.
    // var lang_code_xml = TTS_URL + "&kind=asr&lang=" + lang_code + "&fmt=srv1";
    var en_xml = TTS_URL + "&kind=asr&lang=en&fmt=srv1";
    var tcn_xml = en_xml + "&tlang=zh-Hans"
    $.ajax({
        url: en_xml,
        type: 'get',
        async: true,
        error: function (r)
        {
            console.log("下载英文字幕失败");
        },
        success: function (r)
        {
            en_arr = parseYoutubeXMLToArray(r);
            console.log(en_arr);
        }
    });
    $.ajax({
        url: tcn_xml,
        type: 'get',
        async: true,
        error: function (r)
        {
            console.log("Auto Subtitle Download: Ajax Error");
        },
        success: function (r)
        {
            cn_arr = parseYoutubeXMLToArray(r);
            console.log('cn_arr: ', cn_arr);
        }
    });
}


// ==== srt字幕我们已经完全处理好了, 保存在result里了, 我们现在保存到用户的电脑里就行了. ====
// 保存javascript字符到用户电脑里
function replacesHtml2Text(result)
{
    result = result.replace(/(<div><br>)*<\/div>/g, '\n');
    result = result.replace(/<div>/g, '');
    /* replaces some html entities */
    result = result.replace(/&nbsp;/g, ' ');
    result = result.replace(/&amp;/g, '&');
    result = result.replace(/&lt;/g, '<');
    result = result.replace(/&gt;/g, '>');
    result = result.replace(/&#39;/g, "'");
    return result;
}



//解析xml成数组
function parseYoutubeXMLToArray(youtube_xml_string)
{
    if (youtube_xml_string === "") {
        return false;
    }
    var text = youtube_xml_string.getElementsByTagName('text');
    var result = ""; // store final SRT result
    var len = text.length;
    var res = [];
    for (var i = 0; i < len; i++) {
        var index = i + 1;
        var content = text[i].textContent.toString();
        content = content.replace(/(<([^>]+)>)/ig, ""); // remove all html tag.
        content = replacesHtml2Text(content);
        res.push(content);
    }
    return res;
}

function sleep(time)
{
    return new Promise(function (resolve, reject)
    {
        setTimeout(function () { resolve() }, time);
    });
}



//获得当前的文字状态
function getCurLang(panel)
{
    for (var index = 0; index < panel.childElementCount; index++) {
        var element = panel.children[index];
        if (element.getAttribute("aria-checked") == "true") {
            var eleChild = element.children[0];
            return eleChild.innerText;
        }
    }
}

function clickButton(panel, pat)
{
    for (var index = 0; index < panel.childElementCount; index++) {
        var element = panel.children[index];
        if (element.innerHTML.match(pat)) {
            element.click();
            return true;
        }
    }
    false;
}

function clickSetting()
{
    var btnArr = document.getElementsByClassName("ytp-button ytp-settings-button");
    console.log('btnArr: ', btnArr);
    if (btnArr.length > 0) {
        var btnSeting = btnArr[0];
        console.log('btnSeting: ', btnSeting);
        btnSeting.click();
        return true;
    }
    return false;
}

async function startPlay()
{
    var btn = document.getElementsByClassName("ytp-large-play-button ytp-button");
    console.log(btn);
    if (btn.length > 0) {
        let b = btn[0]
        if (b.formAction.match(/embed/)) {
            btn[0].click();
            sleep(300)
        }
    }
}

//自动切换到中文模式
async function toggleToChinese()
{
    openSubtitle();
    startPlay();
    if (!clickSetting()) {
        return;
    }
    await sleep(1500)
    var panel = document.querySelector("#ytp-id-18 > div > div");
    clickButton(panel, /字幕/)
    await sleep(300)
    var panel2 = document.querySelector("#ytp-id-18 > div > div.ytp-panel-menu");

    if (clickButton(panel2, "中文")) {
        clickSetting();
        return;
    }
    else {
        registerSubtitleChange()
    }
    // clickButton(panel2, /自动翻译/)
    // await sleep(300)
    // let panel3 = document.querySelector("#ytp-id-18 > div > div.ytp-panel-menu")
    // panel3.children[102].click();//点击到中文.
    // clickSetting();
}

//注册字幕事件
function registerSubtitleChange()
{
    let cn_el;
    var lastStr;
    setInterval(() =>
    {
        let el = document.querySelector("#caption-window-1")
        if (el) {
            cn_el = document.getElementById("cn_el");
            if (!cn_el) {
                cn_el = document.createElement("div");
                cn_el.id = "cn_el"
                cn_el.style = 'background: rgba(8, 8, 8, 0.75); -webkit-box-decoration-break: clone; border-radius: 2.66667px; font-size: 21.3333px; color: rgb(229, 229, 229); fill: rgb(229, 229, 229); font-family: "YouTube Noto", Roboto, "Arial Unicode Ms", Arial, Helvetica, Verdana, "PT Sans Caption", sans-serif;'
                cn_el.style.zIndex = 1000;
                cn_el.style.left = "100px"
                cn_el.style.top = "500px"
                cn_el.style.position = "absolute"
                document.body.appendChild(cn_el)
                $(function ()
                {
                    $("#cn_el").draggable();
                });
            }
            var arr = el.innerText.split("\n")
            let cn_index;
            if (arr.length >= 2) {

                if (lastStr == arr[0])
                { return; }
                lastStr = arr[0];
                for (var index = 0; index < en_arr.length; index++) {
                    var element = en_arr[index];
                    if (element.match(new RegExp(arr[0].trim(), "i"))) {
                        cn_index = index;
                        break;
                    }
                }
            }
            cn_el.innerText = en_arr.map(o => o).splice(cn_index - 1, 3).concat(cn_arr.map(o => o).splice(cn_index - 1, 3)).join("\n");
        }
    }, 300)
}




